package com.thoughtworks.util.http;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.httpclient.NameValuePair;

public class AndrosphereUtils {
    public static Map<String, String> convertToMap(NameValuePair[] requestHeaders) {
        final Map<String, String> data = new HashMap<String, String>();

        if(requestHeaders == null) {
            return data;
        }

        CollectionUtils.forAllDo(Arrays.asList(requestHeaders), new Closure() {
            public void execute(Object input) {
                NameValuePair pair = (NameValuePair) input;
                data.put(pair.getName(), pair.getValue());
            }
        });

        return data;
    }

    public static NameValuePair[] convertToNameValuePair(Map<String, String> data) {
        if(data == null) {
            return new NameValuePair[0];
        }

        Collection pairs = CollectionUtils.collect(data.entrySet(), new Transformer() {
            public Object transform(Object input) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) input;
                return new NameValuePair(entry.getKey(), entry.getValue());
            }
        });

        return (NameValuePair[]) pairs.toArray(new NameValuePair[0]);
    }
}
